package com.md.application.service;

import com.md.api.AppInfoApi;
import com.md.base.exception.ServerException;
import com.md.domain.model.po.AppInfoPO;
import com.md.domain.service.AppDomainService;
import com.md.infrastructure.value.ErrorEnum;
import com.md.model.page.PageResponse;
import com.md.model.system.CommonResult;
import com.md.request.AppInfoRequest;
import com.md.request.LinkModuleRequest;
import com.md.request.QueryAppInfoRequest;
import com.md.response.AppInfoResponse;
import com.md.util.ObjectUtil;
import com.md.value.constants.DefaultServerContext;
import com.md.value.server.ServerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.md.application.assembler.AppInfoAssembler.buildAppInfoPO2Response;
import static com.md.application.assembler.AppInfoAssembler.buildAppInfoRequest2PO;
import static com.md.application.assembler.AppInfoAssembler.buildQueryAppInfoBO;
import static com.md.application.assembler.AppInfoAssembler.checkParamValue;

/**
 * @author 刘骄阳
 * 2022-09-24 1:35
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppInfoApplicationService implements AppInfoApi {
  private final AppDomainService appDomainService;

  @Override
  public CommonResult<AppInfoResponse> query(final QueryAppInfoRequest request) {
    List<AppInfoResponse> list = appDomainService.queryAppInfo(buildQueryAppInfoBO(request));
    if (ObjectUtil.isEmpty(list)) {
      throw ServerException.of(ErrorEnum.APP_INFO_NOT_EXIST);
    }
    return CommonResult.success(list.get(0));
  }

  @Override
  public CommonResult<PageResponse<AppInfoResponse>> queryList(final QueryAppInfoRequest request) {
    return CommonResult.success(appDomainService.queryAppInfoByPage(buildQueryAppInfoBO(request)));
  }

  @Override
  public CommonResult<AppInfoResponse> create(final AppInfoRequest request) {
    // 密钥应该每个模块不一样
    AppInfoPO appInfoPO = buildAppInfoRequest2PO(request);
    appDomainService.createAppInfo(appInfoPO, request.getModuleId());
    return CommonResult.success(buildAppInfoPO2Response(appInfoPO));
  }

  @Override
  public CommonResult<AppInfoResponse> update(final AppInfoRequest request) {
    checkParamValue(request.getId(), null, null, null, null);
    AppInfoPO appInfoPO = buildAppInfoRequest2PO(request);
    appDomainService.updateAppInfo(appInfoPO);
    return CommonResult.success(buildAppInfoPO2Response(appInfoPO));
  }

  @Override
  public CommonResult<Void> linkModule(final LinkModuleRequest request) {
    String userId = ServerContext.getLong(DefaultServerContext.USER_ID).toString();
    appDomainService.checkUserModule(request.getModuleId(), userId);
    appDomainService.linkModule(request.getModuleId(), request.getAppInfoIds());
    return CommonResult.success();
  }
}
